package com.sise.netty.netty接收http请求;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import static io.netty.buffer.Unpooled.copiedBuffer;

/**
 * @author idea
 * @data 2019/4/26
 */
public class NettyHttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) throws Exception {
        System.out.println(fullHttpRequest);
        String result = "recive msg";
        FullHttpResponse response = null;
        if (fullHttpRequest.method() == HttpMethod.GET) {
            System.out.println("this is get method");
        } else if (fullHttpRequest.getMethod() == HttpMethod.POST) {
            System.out.println("this is post method");
        }
        ByteBuf byteBuf = copiedBuffer(result, CharsetUtil.UTF_8);

        //响应数据交还给客户端
        response = responseOk(HttpResponseStatus.OK, null);
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    /**
     * 响应请求给客户端
     *
     * @param status
     * @param content
     * @return
     */
    private FullHttpResponse responseOk(HttpResponseStatus status, ByteBuf content) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, content);
        if (content != null) {
            response.headers().set("Content-Type", "text/plain;charset=UTF-8");
            response.headers().set("Content_Length", response.content().readableBytes());
        }
        return response;
    }
}
